﻿using Lg.Core.AliHelper;
using Lg.Core.Extensions;
using Lg.Core.Pay;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Security;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static Org.BouncyCastle.Math.EC.ECCurve;
using Org.BouncyCastle.Crypto.Prng;
using Microsoft.AspNetCore.Mvc.RazorPages;
using NPOI.OpenXmlFormats.Spreadsheet;
using Microsoft.AspNetCore.Http;
using System.Web;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Asn1.Ocsp;

namespace Lg.Core.WxHelper.TenPay.V2
{
    public class Pay : IPay
    {
        private PayConfig _config;
        private HttpContext? _context;

        #region [构造方法]
        public Pay(HttpContext? context=null)
        {
            _context = context;
            JsonHelper jsonHelper = new JsonHelper();
            _config = new PayConfig()
            {
                appid = jsonHelper.GetValue("TenPayV2.appid"),
                appsecret = jsonHelper.GetValue("TenPayV2.appsecret"),
                mch_id = jsonHelper.GetValue("TenPayV2.mch_id"),
                key = jsonHelper.GetValue("TenPayV2.key"),
                notifyurl = jsonHelper.GetValue("TenPayV2.NotifyUrl")
            };
        }
        public Pay(PayConfig config)
        {
            _config = config;
        }
        public Pay(string appid, string appsecret, string mch_id, string key, string notifyurl)
        {
            _config = new PayConfig
            {
                appid = appid,
                appsecret = appsecret,
                mch_id = mch_id,
                key = key,
                notifyurl = notifyurl
            };
        }
        #endregion

        IPayResult? IPay.WapPay(IPayParam param)
        {
            TenPayParam? tpp=param as TenPayParam??throw new Exception("支付参数序列化失败！");
            //统一下单
            TenPayData data = new TenPayData(_config);
            data.SetValue("body", tpp.body);
            data.SetValue("attach", tpp.attach);
            data.SetValue("out_trade_no", tpp.out_trade_no);
            data.SetValue("total_fee", tpp.total_fee);
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
            data.SetValue("goods_tag", tpp.goods_tag??"");
            data.SetValue("trade_type", "JSAPI");
            data.SetValue("openid", tpp.openid);
            TenPayData result = this.UnifiedOrder(data, 6);
            if (!result.IsSet("appid") || !result.IsSet("prepay_id") || result.GetValue("prepay_id").ToString() == "")
            {
                Log.Error(this.GetType().ToString(), "UnifiedOrder response error!");
                throw new Exception(result.ToJson());
            }
            //封装jsapi支付参数
            Log.Debug(this.GetType().ToString(), "JsApiPay::GetJsApiParam is processing...");
            TenPayData jsApiParam = new TenPayData(_config);
            jsApiParam.SetValue("appId", result.GetValue("appid"));
            jsApiParam.SetValue("timeStamp", GenerateTimeStamp());
            jsApiParam.SetValue("nonceStr", GenerateNonceStr());
            jsApiParam.SetValue("package", "prepay_id=" + result.GetValue("prepay_id"));
            jsApiParam.SetValue("signType", "MD5");
            jsApiParam.SetValue("paySign", jsApiParam.MakeSign());
            string parameters = jsApiParam.ToJson();
            Log.Debug(this.GetType().ToString(), "Get jsApiParam : " + parameters);
            return new TenPayResult() { code=0,msg="success",data=parameters};
        }

        #region [私有方法]
        private TenPayData UnifiedOrder(TenPayData tpd, int timeOut)
        {

            string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            //检测必填参数
            if (!tpd.IsSet("out_trade_no"))
            {
                throw new Exception("缺少统一支付接口必填参数out_trade_no！");
            }
            else if (!tpd.IsSet("body"))
            {
                throw new Exception("缺少统一支付接口必填参数body！");
            }
            else if (!tpd.IsSet("total_fee"))
            {
                throw new Exception("缺少统一支付接口必填参数total_fee！");
            }
            else if (!tpd.IsSet("trade_type"))
            {
                throw new Exception("缺少统一支付接口必填参数trade_type！");
            }

            //关联参数
            if (tpd.GetValue("trade_type").ToString() == "JSAPI" && !tpd.IsSet("openid"))
            {
                throw new Exception("统一支付接口中，缺少必填参数openid！trade_type为JSAPI时，openid为必填参数！");
            }
            if (tpd.GetValue("trade_type").ToString() == "NATIVE" && !tpd.IsSet("product_id"))
            {
                throw new Exception("统一支付接口中，缺少必填参数product_id！trade_type为JSAPI时，product_id为必填参数！");
            }

            //异步通知url未设置，则使用配置文件中的url
            if (!tpd.IsSet("notify_url"))
            {
                tpd.SetValue("notify_url", _config.notifyurl);//异步通知url
            }
            tpd.SetValue("appid", _config.appid);
            tpd.SetValue("mch_id", _config.mch_id);//商户号
            tpd.SetValue("spbill_create_ip", _config.ip??"");//终端ip	  	    
            tpd.SetValue("nonce_str", GenerateNonceStr());//随机字符串
            tpd.SetValue("sign_type", TenPayData.SIGN_TYPE_MD5);//签名类型
            //签名
            tpd.SetValue("sign", tpd.MakeSign());
            string xml = tpd.ToXml();
            var start = DateTime.Now;
            Log.Debug("WxPayApi", "UnfiedOrder request : " + xml);
            string response = Post(xml, url, false, timeOut);
            Log.Debug("WxPayApi", "UnfiedOrder response : " + response);

            var end = DateTime.Now;
            int timeCost = (int)((end - start).TotalMilliseconds);

            TenPayData result = new TenPayData(_config);
            result.FromXml(response);
            return result;
        }

        private bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            //直接确认，否则打不开    
            return true;
        }

        private string Post(string xml, string url, bool isUseCert, int timeout)
        {
            System.GC.Collect();//垃圾回收，回收没有正常关闭的http连接

            string result = "";//返回结果
            string USER_AGENT = string.Format("WXPaySDK/{3} ({0}) .net/{1} {2}", Environment.OSVersion, Environment.Version, _config.mch_id, typeof(Pay).Assembly.GetName().Version);
            HttpWebRequest? request = null;
            HttpWebResponse? response = null;
            Stream? reqStream = null;

            try
            {
                //设置最大连接数
                ServicePointManager.DefaultConnectionLimit = 200;
                //设置https验证方式
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback =
                            new RemoteCertificateValidationCallback(CheckValidationResult);
                }

                /***************************************************************
                * 下面设置HttpWebRequest的相关属性
                * ************************************************************/
                request = (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent = USER_AGENT;
                request.Method = "POST";
                request.Timeout = timeout * 1000;

                //设置代理服务器
                //WebProxy proxy = new WebProxy();                          //定义一个网关对象
                //proxy.Address = new Uri(WxPayConfig.PROXY_URL);              //网关服务器端口:端口
                //request.Proxy = proxy;

                //设置POST的数据类型和长度
                request.ContentType = "text/xml";
                byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
                request.ContentLength = data.Length;

                //是否使用证书
                if (isUseCert)
                {
                    X509Certificate2 cert = new X509Certificate2($@"{_config.sslcertpath}", _config.sslcertpassword);
                    request.ClientCertificates.Add(cert);
                    Log.Debug("WxPayApi", "PostXml used cert");
                }

                //往服务器写入数据
                reqStream = request.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();

                //获取服务端返回
                response = (HttpWebResponse)request.GetResponse();

                //获取服务端返回数据
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                sr.Close();
            }
            catch (System.Threading.ThreadAbortException e)
            {
                Log.Error("HttpService", "Thread - caught ThreadAbortException - resetting.");
                Log.Error("Exception message: {0}", e.Message);
                System.Threading.Thread.ResetAbort();
            }
            catch (WebException e)
            {
                Log.Error("HttpService", e.ToString());
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    Log.Error("HttpService", "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode);
                    Log.Error("HttpService", "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription);
                }
                throw new Exception(e.ToString());
            }
            catch (Exception e)
            {
                Log.Error("HttpService", e.ToString());
                throw new Exception(e.ToString());
            }
            finally
            {
                //关闭连接和流
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }
            return result;
        }

        /// <summary>
        /// 处理http GET请求，返回数据
        /// </summary>
        /// <param name="url">请求的url地址</param>
        /// <returns>http GET成功后返回的数据，失败抛WebException异常</returns>
        private string Get(string url)
        {
            System.GC.Collect();
            string result = "";
            string USER_AGENT = string.Format("WXPaySDK/{3} ({0}) .net/{1} {2}", Environment.OSVersion, Environment.Version, _config.mch_id, typeof(Pay).Assembly.GetName().Version);
            HttpWebRequest request = null;
            HttpWebResponse response = null;

            //请求url以获取数据
            try
            {
                //设置最大连接数
                ServicePointManager.DefaultConnectionLimit = 200;
                //设置https验证方式
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback =
                            new RemoteCertificateValidationCallback(CheckValidationResult);
                }

                /***************************************************************
                * 下面设置HttpWebRequest的相关属性
                * ************************************************************/
                request = (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent = USER_AGENT;
                request.Method = "GET";

                //获取服务器返回
                response = (HttpWebResponse)request.GetResponse();

                //获取HTTP返回数据
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                sr.Close();
            }
            catch (System.Threading.ThreadAbortException e)
            {
                Log.Error("HttpService", "Thread - caught ThreadAbortException - resetting.");
                Log.Error("Exception message: {0}", e.Message);
                System.Threading.Thread.ResetAbort();
            }
            catch (WebException e)
            {
                Log.Error("HttpService", e.ToString());
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    Log.Error("HttpService", "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode);
                    Log.Error("HttpService", "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription);
                }
                throw new Exception(e.ToString());
            }
            catch (Exception e)
            {
                Log.Error("HttpService", e.ToString());
                throw new Exception(e.ToString());
            }
            finally
            {
                //关闭连接和流
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }
            return result;
        }

        /**
        * 根据当前系统时间加随机序列来生成订单号
         * @return 订单号
        */
        private string GenerateOutTradeNo()
        {
            System.Random ran = new System.Random();
            return string.Format("{0}{1}{2}", _config.mch_id, DateTime.Now.ToString("yyyyMMddHHmmss"), ran.Next(999));
        }

        /**
        * 生成时间戳，标准北京时间，时区为东八区，自1970年1月1日 0点0分0秒以来的秒数
         * @return 时间戳
        */
        private string GenerateTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

        /**
        * 生成随机串，随机串包含字母或数字
        * @return 随机串
        */
        private string GenerateNonceStr()
        {
            RandomGenerator randomGenerator = new RandomGenerator();
            return randomGenerator.GetRandomUInt().ToString();
        }

        /// <summary>
        /// 接收从微信支付后台发送过来的数据并验证签名
        /// </summary>
        /// <returns>微信支付后台返回的数据</returns>
        public  TenPayData GetNotifyData(string notifyData)
        {
            //接收从微信后台POST过来的数据
            Log.Info("GetNotifyData", "Receive data from WeChat : " + notifyData);
            //转换数据格式并验证签名
            TenPayData res = new TenPayData(_config);
            try
            {
                res.FromXml(notifyData);
                Log.Info("GetNotifyData", "Check sign success");
            }
            catch (Exception ex)
            {
                //若签名错误，则立即返回结果给微信支付后台
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", ex.Message);
                Log.Error("GetNotifyData", "Sign check error : " + res.ToXml());
            }

            return res;
        }

        public void GetCode(string redirect_uri)
        {
            if(_context == null)
            {
                throw new Exception("缺少HttpContext对像，请在构造Pay实例是提供当前请求的HttpContext对像");
            }
            //构造网页授权获取code的URL
            redirect_uri = HttpUtility.UrlEncode(redirect_uri);
            TenPayData data = new TenPayData(null);
            data.SetValue("appid",  _config.appid??"");
            data.SetValue("redirect_uri", redirect_uri);
            data.SetValue("response_type", "code");
            data.SetValue("scope", "snsapi_base");
            data.SetValue("state", "STATE" + "#wechat_redirect");
            string url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + data.ToUrl();
            try
            {
                _context.Response.Redirect(url);
            }
            catch (Exception ex)
            {
                Log.Info(ex.Message, "error");
                throw new Exception(ex.Message);
            }
        }

        /**
       * 
       * 通过code换取网页授权access_token和openid的返回数据，正确时返回的JSON数据包如下：
       * {
       *  "access_token":"ACCESS_TOKEN",
       *  "expires_in":7200,
       *  "refresh_token":"REFRESH_TOKEN",
       *  "openid":"OPENID",
       *  "scope":"SCOPE",
       *  "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
       * }
       * 其中access_token可用于获取共享收货地址
       * openid是微信支付jsapi支付接口统一下单时必须的参数
       * 更详细的说明请参考网页授权获取用户基本信息：http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
       * @失败时抛异常WxPayException
       */
        public JObject GetOpenidAndAccessTokenFromCode(string code)
        {
            try
            {
                //构造获取openid及access_token的url
                TenPayData data = new TenPayData(null);
                data.SetValue("appid", _config.appid!);
                data.SetValue("secret", _config.appsecret!);
                data.SetValue("code", code);
                data.SetValue("grant_type", "authorization_code");
                string url = "https://api.weixin.qq.com/sns/oauth2/access_token?" + data.ToUrl();
                //请求url以获取数据
                string result = this.Get(url);
                Log.Debug(this.GetType().ToString(), "GetOpenidAndAccessTokenFromCode response : " + result);
                return result.ToJobject();                
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
        #endregion

    }
}
